<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/5/23
 * Time: 14:56
 */

namespace p5\encrypt;


class EcbDesUtils
{
    public function encrypt($string, $key)
    {
        $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_DES, MCRYPT_MODE_ECB), MCRYPT_RAND);
        $decrypted = mcrypt_encrypt(MCRYPT_DES, $key, $string, MCRYPT_MODE_ECB, $iv);
        $encode = base64_encode($decrypted);
        return $encode;
    }

    public function decrypt($string, $key)
    {
        $decoded = base64_decode($string);
        $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_DES, MCRYPT_MODE_ECB), MCRYPT_RAND);
        $decrypted = mcrypt_decrypt(MCRYPT_DES, $key, $decoded, MCRYPT_MODE_ECB, $iv);
        return $this->trimEnd($decrypted);
    }

    private function trimEnd($text)
    {
        $len = strlen($text);
        $c = $text[$len - 1];

        if (ord($c) == 0) return rtrim($text, $c);
        if (ord($c) < $len) {
            for ($i = $len - ord($c); $i < $len; $i++) {
                if ($text[$i] != $c) {
                    return $text;
                }
            }
            return substr($text, 0, $len - ord($c));
        }
        return $text;
    }
}